<?php

namespace app\controller;

use app\BaseController;
use app\model\AdminPermissions;
use app\model\AdminRolePermissions;
use think\Request;
use app\model\AdminRoles;
use app\model\AdminMenu;
use app\model\AdminRoleMenus;
use think\facade\Db;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use think\db\exception\DbException;
use think\Validate;
use think\facade\Request as RequestFacade;

class Role extends BaseController {

    // 预定义角色标识常量
    const SUPER_ADMIN = 'superadmin';
    const ADMIN = 'admin';
    const OPERATION = 'operation';

    public function index()
    {

        //https://steamadmin.spacetime2024.online/index.php/roles?name=Administrator
        //如果name=Administrator, 返回 true

        // 获取搜索条件
        $username = $this->request->get('name', '');
        //if ($username == 'Administrator'){
        //    return true;
        //}
        $slug = $this->request->get('slug', '');

        // 构建角色查询
        $query = Db::name('admin_roles');

        if (!empty($username)) {
            $query->whereExists(function ($subQuery) use ($username) {
                $subQuery->table('admin_role_users')
                    ->join('admin_users', 'admin_role_users.user_id = admin_users.id')
                    ->whereRaw('admin_role_users.role_id = admin_roles.id');
            });
        }

        if (!empty($slug)) {
            $query->where('slug', 'like', "%{$slug}%");
        }
        if (!empty($username)) {
            $query->where('name', 'like', "%{$username}%");
        }

        // 分页查询角色
        $roles = $query->paginate(10);

        // 获取每个角色对应的菜单
        $roleIds = [];
        foreach ($roles as $role) {
            $roleIds[] = $role['id'];
        }

        if (!empty($roleIds)) {
            $roleMenuResults = Db::name('admin_role_menu')
                ->whereIn('role_id', $roleIds)
                ->where("admin_menu.show","=","1")
                ->join('admin_menu', 'admin_role_menu.menu_id = admin_menu.id')
                ->field('admin_role_menu.role_id, admin_menu.*')
                ->select();

            $roleMenus = [];
            foreach ($roleMenuResults as $menu) {
                $roleId = $menu['role_id'];
                if (!isset($roleMenus[$roleId])) {
                    $roleMenus[$roleId] = [];
                }
                $roleMenus[$roleId][] = $menu;
            }
        } else {
            $roleMenus = [];
        }

        // 整合角色和菜单信息
        $result = [];
        foreach ($roles as $role) {
            $roleData = $role;
            $roleData['menus'] = $roleMenus[$role['id']] ?? [];
            $result[] = $roleData;
        }

        return json([
            'code' => 0,
            'msg' => 'OK',
            'data' => [
                'roles' => $result,
                'total' => $roles->total(),
                'current_page' => $roles->currentPage(),
                'per_page' => $roles->listRows()
            ]
        ]);
    }


    public function create(Request $request)
    {
        $data = $request->post([
        'slug' => '',
            'name' => '',
        'menu_ids' => []
        ]);

        // 验证规则
        $validate = new Validate([
        'slug' =>'require|unique:admin_roles',
            'name' =>'require'
        ]);

        if (!$validate->check($data)) {
            return json(['code' => 400,'msg' => $validate->getError()]);
        }

        try {
            Db::startTrans();

            // 创建角色
            $role = AdminRoles::create([
            'slug' => $data['slug'],
                'name' => $data['name']
            ]);

            // 处理菜单绑定（使用模型的关联关系）
            if (!empty($data['menu_ids'])) {
                // 验证所有菜单ID有效性
                $menuList = AdminMenu::whereIn('id', $data['menu_ids'])->select();
                $validMenuIds = [];
                $invalidMenuIds = [];
                foreach ($data['menu_ids'] as $menuId) {
                    $found = false;
                    foreach ($menuList as $menu) {
                        if ($menu->id == $menuId) {
                            $validMenuIds[] = $menuId;
                            $found = true;
                            break;
                        }
                    }
                    if (!$found) {
                        $invalidMenuIds[] = $menuId;
                    }
                }

                if (!empty($invalidMenuIds)) {
                    throw new \Exception('包含无效的菜单ID: '. implode(', ', $invalidMenuIds));
                }

                // 使用sync方法同步关联（自动处理中间表）
                $role->menus()->sync($validMenuIds);
            }

            Db::commit();
            return json(['code' => 0,'msg' => '角色创建成功']);
        } catch (\Exception $e) {
            Db::rollback();
            return json([
                'code' => 1,
            'msg' => '操作失败：'. $e->getMessage()
            ]);
        }
    }




    protected function resolveMenuTree($selectedIds, $allMenus): array
    {
        // 1. 强制转换$selectedIds为数组（处理字符串/空值情况）
        $selectedIds = is_string($selectedIds)
            ? explode(',', $selectedIds)  // 处理"1,2,3"格式的字符串
            : (array)$selectedIds;         // 处理null/非数组类型

        // 2. 过滤无效ID（可选增强）
        $selectedIds = array_filter($selectedIds, 'is_numeric');

        $menuMap = array_column($allMenus, null, 'id');
        $result = [];

        foreach ($selectedIds as $id) {  // 现在确保是数组类型
            if (!isset($menuMap[$id])) {
                continue;
            }

            // 递归获取父级
            $parent = $this->resolveParent($id, $menuMap);
            if ($parent) {
                $result = array_merge($result, $parent);
            }

            $result[] = $menuMap[$id];
        }

        return array_values(array_unique($result, SORT_REGULAR));
    }


    // 新增：递归获取父级节点（示例）
    protected function resolveParent($id, $menuMap, &$parentList = [])
    {
        $menu = $menuMap[$id] ?? null;
        if ($menu && $menu['parent_id'] !== 0) {
            $parentList[] = $menuMap[$menu['parent_id']];
            $this->resolveParent($menu['parent_id'], $menuMap, $parentList);
        }
        return $parentList;
    }


    /**
     * 提供给前端的菜单树接口
     */
    public function getMenuTree()
    {
        return json([
            'code' => 0,
            'data' => $this->buildMenuTree()
        ]);
    }


    public function update(Request $request, $id)
    {
        $data = $request->post();
        
        // 验证数据（示例规则）
        $validate = validate('AdminRoleValidate');
        if (!$validate->scene('update')->check($data)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }

        // 提取菜单ID（注意去除非法值）
        $menuIds = array_filter($data['menu_ids'] ?? [], 'is_numeric');

        // 开始事务
        $role = AdminRoles::findOrEmpty($id);
        if ($role->isEmpty()) {
            return json(['code' => 404, 'msg' => '角色不存在']);
        }

        try {
            // 更新角色基本信息
            $role->save([
                'slug' => $data['slug'],
                'name' => $data['name'],
            ]);

            // 同步菜单关联（重点修改部分）
            $role->menus()->sync($menuIds);

            return json(['code' => 0, 'msg' => '更新成功']);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '操作失败：' . $e->getMessage()]);
        }
    }

    public function delete($id)
    {
        $role = AdminRoles::find($id);
        if (!$role) {
            return json(['code' => 404, 'message' => '角色不存在']);
        }

        // 检查是否为预定义角色
        $protectedSlugs = [Role::SUPER_ADMIN, Role::ADMIN, Role::OPERATION];
        if (in_array($role->slug, $protectedSlugs)) {
            return json(['code' => 403, 'message' => '系统内置角色不可删除']);
        }

        $role->delete();
        return json(['code' => 0, 'message' => '删除成功']);
    }


    public function export(Request $request)
    {
        $search = request()->get('search');
        $slug = request()->get('slug');

        $query = AdminRoles::where(true);

        if ($search) {
            $query->where('name', 'like', "%{$search}%");
        }

        if ($slug) {
            $query->where('slug', 'like', "%{$slug}%");
        }

        $roles = $query->select();

        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $sheet->setCellValue('A1', 'ID');
        $sheet->setCellValue('B1', '角色名称');
        $sheet->setCellValue('C1', '角色标识');

        $row = 2;
        foreach ($roles as $role) {
            $sheet->setCellValue('A' . $row, $role->id);
            $sheet->setCellValue('B' . $row, $role->name);
            $sheet->setCellValue('C' . $row, $role->slug);
            $row++;
        }

        // 获取当前日期
        $date = date('Ymd');
        // 定义新的文件名
        $newFileName = $date . '_role_export.xlsx';

        $writer = new Xlsx($spreadsheet);
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        // 使用新的文件名
        header('Content-Disposition: attachment;filename="'.$newFileName.'"');
        header('Cache-Control: max-age=0');
        $writer->save('php://output');

    }


}